var express = require('express');
var router = express.Router();
const db = require('../config/db');
const { v4: uuidv4 } = require('uuid');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 添加注册路由
router.post('/signup', async function(req, res) {
    try {
        const {
            name, gender, birth_year, hometown, contact,
            work_location, education, marital_status_desc,
            height, weight, zodiac, occupation, income,
            family, housing, hobbies, personality,
            accept_divorced, requirements, introduction
        } = req.body;

        // 基本字段验证
        const requiredFields = {
            name, gender, birth_year, hometown, contact,
            work_location, education, marital_status_desc,
            height, occupation, income, housing,
            hobbies, personality, requirements, introduction
        };

        // 检查必填字段
        for (const [field, value] of Object.entries(requiredFields)) {
            if (!value) {
                return res.status(400).json({
                    code: 400,
                    msg: `${field} 为必填项`,
                    data: null
                });
            }
        }

        // 验证手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(contact)) {
            return res.status(400).json({
                code: 400,
                msg: '手机号格式不正确',
                data: null
            });
        }

        // 验证性别枚举值
        if (!['男', '女'].includes(gender)) {
            return res.status(400).json({
                code: 400,
                msg: '性别只能是 male 或 female',
                data: null
            });
        }

        // 验证教育程度枚举值
        const validEducation = ['juniorHigh', 'highschool', 'college', 'bachelor'];
        if (!validEducation.includes(education)) {
            return res.status(400).json({
                code: 400,
                msg: '教育程度不符合要求',
                data: null
            });
        }

        // 验证收入范围枚举值
        const validIncome = ['<3000', '3000-5000', '5000-8000', '8000-12000'];
        if (!validIncome.includes(income)) {
            return res.status(400).json({
                code: 400,
                msg: '收入范围不符合要求',
                data: null
            });
        }

        // 验证住房情况枚举值
        if (!['rent', 'own', 'shared'].includes(housing)) {
            return res.status(400).json({
                code: 400,
                msg: '住房情况只能是 rent、own 或 shared',
                data: null
            });
        }

        // 检查手机号是否已存在
        const [existingUsers] = await db.pool.query(
            'SELECT id FROM users WHERE contact = ?',
            [contact]
        );

        if (existingUsers.length > 0) {
            return res.status(400).json({
                code: 400,
                msg: '该手机号已被注册',
                data: null
            });
        }

        // 生成UUID作为用户ID
        const id = uuidv4();

        // 插入新用户
        const [result] = await db.pool.query(
            `INSERT INTO users (
                id, name, gender, birth_year, hometown, contact,
                work_location, education, marital_status_desc,
                height, weight, zodiac, occupation, income,
                family, housing, car, hobbies, personality,
                accept_divorced, requirements, introduction
            ) VALUES (
                ?, ?, ?, ?, ?, ?, 
                ?, ?, ?, 
                ?, ?, ?, ?, ?,
                ?, ?, DEFAULT, ?, ?,
                ?, ?, ?
            )`,
            [
                id, name, gender, birth_year, hometown, contact,
                work_location, education, marital_status_desc,
                height, weight || null, zodiac || null, occupation, income,
                family || null, housing, hobbies, personality,
                accept_divorced || false, requirements, introduction
            ]
        );

        res.status(200).json({
            code: 200,
            msg: '注册成功',
            data: {
                id,
                name,
                contact
            }
        });

    } catch (error) {
        console.error('注册失败:', error);
        res.status(500).json({
            code: 500,
            msg: '服务器错误，注册失败',
            data: null
        });
    }
});

// 添加测试路由
router.get('/testdb', async function(req, res) {
    try {
        const [result] = await db.pool.query('SELECT 1 + 1 AS solution');
        res.status(200).json({
            code: 200,
            msg: '数据库连接成功',
            data: result[0]
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '数据库连接失败',
            data: null
        });
    }
});

module.exports = router;
